import React, { Component } from 'react'
import axios from 'axios'

export default class Todolist extends Component {
    state={
        list:[],
        username:"",
        age:0
    }
    componentDidMount(){
        this.getData()
    }
    getData = ()=>{
        axios.get("http://localhost:4000/list").then(res=>{
            this.setState({
                list:res.data
            })
        })
    }
    handleChange = e=>{
        this.setState({
            [e.target.id] : e.target.value
        })
    }
    add = ()=>{
        axios.post("http://localhost:4000/list",{
            username:this.state.username,
            age:this.state.age
        }).then(res=>{
            //重新请求后端数据
            this.getData()
            //请求输入框的值
            this.setState({username:"",age:0})
        })
    }
    delete = (id)=>{
        axios.delete("http://localhost:4000/list/"+id).then(res=>{
            this.getData()
        })
    }
    update = ({username,age,id})=>{
        let value = prompt("请输入修改的内容",username+","+age)
        let arr = value.split(",")
        axios.patch("http://localhost:4000/list/"+id,{
            username:arr[0],
            age:arr[1]
        }).then(res=>{
           this.getData()
        })
    }
    render() {
        let {username,age,list} = this.state
        return (
            <div>
                <input type="text" id = "username" placeholder="请输入用户名。。。" value={username} onChange = {this.handleChange}/>
                <input type="number" id="age" placeholder="请输入年龄。。。" value = {age} onChange = {this.handleChange}/>
                <button onClick={this.add}>添加</button>
               <ul>
               {
                    list.map((item)=>{
                return (<li key={item.id}>{item.username}---{item.age}
                <button onClick = {this.delete.bind(this,item.id)}>删除</button>
                <button onClick = {this.update.bind(this,item)}>修改</button>
                </li>)
                    })
                }
               </ul>
            </div>
        )
    }
}
